package com.activemq.maintance;

import cn.hutool.core.date.DateUtil;
import com.activemq.MqHelloWorld;
import lombok.extern.slf4j.Slf4j;
import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;

@Slf4j
public class JdbcTopicSub {
    public static final String JDBC_TOPIC = "JDBC_TOPIC";

    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.setClientID("wangwy16");
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(JDBC_TOPIC);
        TopicSubscriber sub = session.createDurableSubscriber(topic, "REMARKS");
        connection.start();
        //持久化订阅
        sub.setMessageListener((msg) -> {
            try {
                log.error("收到了来自XXX的消息！！！" + ((TextMessage) msg).getText());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        });
        System.in.read();
        sub.close();
        session.close();
        connection.close();
    }
}

class Sender {
    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(JdbcTopicSub.JDBC_TOPIC);
        MessageProducer producer = session.createProducer(topic);
        for (int i = 0; i < 3; i++) {
            producer.send(session.createTextMessage("测试发送JDBC消息：" + DateUtil.now() + "_" + i));
        }
        producer.close();
        session.close();
        connection.close();
    }
}

@Slf4j
class Recer {
    public static void main(String[] args) throws Exception {
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(MqHelloWorld.URL);
        Connection connection = factory.createConnection();
        connection.setClientID("wangwy16");
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(JdbcTopicSub.JDBC_TOPIC);
        MessageConsumer consumer = session.createConsumer(topic);
        consumer.setMessageListener((msg) -> {
            try {
                log.error("收到了来自XXX的消息！！！" + ((TextMessage) msg).getText());
            } catch (JMSException e) {
                throw new RuntimeException(e);
            }
        });
        System.in.read();
        consumer.close();
        session.close();
        connection.close();
    }
}